import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './LoginPage.css'; // 单独的样式文件

function LoginPage() {
  const [loginType, setLoginType] = useState('password'); // 'password' 或 'wechat' 或 'phone'
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    phone: '',
    code: ''
  });
  const [errors, setErrors] = useState({});
  const [verificationCode, setVerificationCode] = useState('');
  const [isSendingCode, setIsSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();

  // 切换登录方式
  const handleLoginTypeChange = (type) => {
    setLoginType(type);
    setErrors({}); // 清除错误信息
  };

  // 表单输入变化处理
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 验证表单（密码登录）
  const validatePasswordLogin = () => {
    const newErrors = {};
    if (!formData.username) newErrors.username = '用户名不能为空';
    if (!formData.password) newErrors.password = '密码不能为空';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 验证表单（手机验证码登录）
  const validatePhoneLogin = () => {
    const newErrors = {};
    if (!formData.phone) newErrors.phone = '手机号不能为空';
    if (!/^\d{11}$/.test(formData.phone)) newErrors.phone = '请输入正确的手机号';
    if (!formData.code) newErrors.code = '验证码不能为空';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 发送验证码
  const sendVerificationCode = async () => {
    if (!validatePhoneField()) return;

    setIsSendingCode(true);
    setCountdown(60);

    try {
      // 模拟发送验证码的API调用
      console.log('发送验证码到:', formData.phone);
      
      // 这里应该是实际的API调用
      // const response = await fetch('/api/send-verification-code', {
      //   method: 'POST',
      //   body: JSON.stringify({ phone: formData.phone }),
      //   headers: { 'Content-Type': 'application/json' }
      // });

      // 模拟倒计时
      const timer = setInterval(() => {
        setCountdown(prev => {
          if (prev <= 1) {
            clearInterval(timer);
            setIsSendingCode(false);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      console.error('发送验证码失败:', error);
      alert('发送验证码失败，请重试');
    }
  };

  // 验证手机号字段
  const validatePhoneField = () => {
    const newErrors = {};
    if (!formData.phone) newErrors.phone = '手机号不能为空';
    if (!/^\d{11}$/.test(formData.phone)) newErrors.phone = '请输入正确的手机号';
    setErrors(prev => ({ ...prev, ...newErrors }));
    return Object.keys(newErrors).length === 0;
  };

  // 手机验证码登录提交
  const handlePhoneLoginSubmit = (e) => {
    e.preventDefault();
    if (validatePhoneLogin()) {
      // 这里处理手机验证码登录逻辑
      console.log('手机验证码登录:', formData);
      
      // 模拟登录成功
      alert('手机验证码登录成功！');
      navigate('/home');
    }
  };

  // 密码登录提交
  const handlePasswordLoginSubmit = (e) => {
    e.preventDefault();
    if (validatePasswordLogin()) {
      // 这里处理密码登录逻辑
      console.log('密码登录:', formData);
      
      // 模拟登录成功
      alert('密码登录成功！');
      navigate('/home');
    }
  };

  // 微信扫码登录（模拟）
  const handleWechatLogin = () => {
    // 这里应该是调用微信OAuth授权的逻辑
    alert('微信扫码登录功能已触发（实际项目中需要集成微信SDK）');
    
    // 模拟扫码成功
    setTimeout(() => {
      alert('微信扫码登录成功！');
      navigate('/home');
    }, 2000);
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2>登录</h2>
        
        {/* 登录方式切换 */}
        <div className="login-type-selector">
          <button 
            className={loginType === 'password' ? 'active' : ''}
            onClick={() => handleLoginTypeChange('password')}
          >
            密码登录
          </button>
          <button 
            className={loginType === 'phone' ? 'active' : ''}
            onClick={() => handleLoginTypeChange('phone')}
          >
            手机验证码登录
          </button>
          <button 
            className={loginType === 'wechat' ? 'active' : ''}
            onClick={() => handleLoginTypeChange('wechat')}
          >
            微信登录
          </button>
        </div>

        {/* 密码登录表单 */}
        {loginType === 'password' && (
          <form onSubmit={handlePasswordLoginSubmit} className="login-form">
            <div className="form-group">
              <label htmlFor="username">用户名</label>
              <input
                type="text"
                id="username"
                name="username"
                value={formData.username}
                onChange={handleChange}
                className={errors.username ? 'error' : ''}
              />
              {errors.username && <span className="error-message">{errors.username}</span>}
            </div>
            
            <div className="form-group">
              <label htmlFor="password">密码</label>
              <input
                type="password"
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                className={errors.password ? 'error' : ''}
              />
              {errors.password && <span className="error-message">{errors.password}</span>}
            </div>
            
            <button type="submit" className="submit-btn">登录</button>
          </form>
        )}

     {/* 手机验证码登录表单 */}
{loginType === 'phone' && (
  <form onSubmit={handlePhoneLoginSubmit} className="login-form">
    <div className="form-group">
      <label htmlFor="phone">手机号</label>
      <input
        type="tel"
        id="phone"
        name="phone"
        value={formData.phone}
        onChange={handleChange}
        className={errors.phone ? 'error' : ''}
        disabled={isSendingCode && countdown > 0}
      />
      {errors.phone && <span className="error-message">{errors.phone}</span>}
    </div>
    
    {/* 验证码部分 */}
    <div className="code-container">
      {/* 验证码标签组 */}
      <div className="form-group code-label-group">
        <label htmlFor="code">验证码</label>
      </div>
      
      {/* 输入框 + 按钮组 */}
      <div className="input-button-group">
        <input
          type="text"
          id="code"
          name="code"
          value={formData.code}
          onChange={handleChange}
          className={errors.code ? 'error' : ''}
        />
   
        
        <button 
          type="button" 
          onClick={sendVerificationCode}
          disabled={isSendingCode || countdown > 0}
          className="code-btn"
        >
          {isSendingCode && countdown > 0 ? `${countdown}s后重发` : '获取验证码'}
        </button>
      </div>
        {/* 错误提示 */}
  {errors.code && <span className="error-message">{errors.code}</span>}
    </div>
    
    <button type="submit" className="submit-btn">登录</button>
  </form>
)}

        {/* 微信登录（模拟） */}
        {loginType === 'wechat' && (
          <div className="wechat-login">
            <p>请使用微信扫描下方二维码登录</p>
            <div className="qr-code-container">
              {/* 这里应该是真实的二维码图片 */}
              <img 
                src="https://via.placeholder.com/200x200?text=微信二维码" 
                alt="微信登录二维码"
              />
            </div>
            <button onClick={handleWechatLogin} className="wechat-btn">
              {isSendingCode && countdown > 0 ? '正在登录...' : '点击登录'}
            </button>
          </div>
        )}

        {/* 底部提示 */}
        <div className="login-footer">
          <p>还没有账号？ <a href="/register">立即注册</a></p>
          <p>其他登录方式：</p>
          <div className="other-login-methods">
            <span>QQ</span>
            <span>微博</span>
            <span>GitHub</span>
          </div>
        </div>
      </div>
    </div>
  );
}

export default LoginPage;